package main

import (
	"context"
	"github.com/gogo/protobuf/proto"
	protos "goim-pro/api/protos/example"
	. "goim-pro/api/protos/salty"
	"goim-pro/pkg/utils"
	"google.golang.org/grpc"
	"log"
)

const (
	address = "localhost:8080"
)

func main() {
	conn, err := grpc.Dial(
		address,
		grpc.WithInsecure(),
		grpc.WithUnaryInterceptor(cellInterceptor),
	)
	if err != nil {
		log.Fatalf("grpc connect fail: %v", err)
	}
	defer conn.Close()

	// create Writer service's client
	t := protos.NewWaiterClient(conn)

	//	调用 gRPC 接口
	tr, err := t.SayHello(context.Background(), &protos.HelloReq{
		Name: "JAMES YANG",
	})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	//log.Printf("服务端响应：%s", tr.BackJson)
	log.Printf("服务端响应：%s", tr)
}

func cellInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	pb := req.(proto.Message)
	anyData, _ := utils.MarshalMessageToAny(pb)
	newReq := &GrpcReq{
		DeviceId: "LOCAL_DEV",
		Version:  "",
		Language: 0,
		Os:       0,
		Token:    "",
		Data:     anyData,
	}
	err := invoker(ctx, method, newReq, reply, cc, opts...)
	return err
}
